package cn.tedu.sp06zuul.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**@Component 交给spring框架自动扫描用来创建实例对象*/
@Component
@Slf4j
public class AccessFilter extends ZuulFilter {
    //过滤器的类型:pre,routing,post,error
    @Override
    public String filterType() {
//        return "pre";
        return FilterConstants.PRE_TYPE;
    }
    //顺序号
    /**/
    @Override
    public int filterOrder() {
        return 6;
    }
    //针对当前请求,是否要执行过滤代码
    //请求商品要检查权限,请求用户和订单不检查权限
    @Override
    public boolean shouldFilter() {
        //判断当前调用的后台服务,是不是item-service
        //先获取调用的服务Id,如果id是item-service,返回true,会执行过滤代码
        RequestContext ctx = RequestContext.getCurrentContext();
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        return "item-service".equals(serviceId);
    }
    //过滤代码
    @Override
    public Object run() throws ZuulException {
        //接收token参数
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String token = request.getParameter("token");
        //如果没有token,阻止继续调用,直接返回响应  null,  ""  ,  "     "
        if (StringUtils.isBlank(token)){
            // 阻止继续调用
            ctx.setSendZuulResponse(false);
            // 直接返回响应
            //JsonResult - {code:xx,msg:xx,data:null}
        String json = JsonResult.err().code(JsonResult.NOT_LOGIN).msg("未登录!!").toString();
        ctx.addZuulResponseHeader("Content_type","application/json;charset=UTF-8");
            ctx.setResponseBody(json);

    }
        return null;
    }
}